clear all

% ----------------------------------------------------------------------- %
% Complete the following code:
% Modify here to your folder
cd 'FILL HERE'

% -------------------------------- END ---------------------------------- %

% Check all the text files in the folder
fileinfo = dir('*.txt');
fnames = {fileinfo.name};


% Imports all data in the folder
for j=1:1:length(fnames)
    filename = fnames{j};
    data{j} = importdata(filename);
end

% Seperates fine and coarse time stamps, finds marker positions
for j=1:1:length(fnames)

    temp = data{1,j};
    coarse = temp(:,2);
    fine = temp(:,1);
    Ind{j} = find(fine == -56); %-56 is the marker for counter reset

end

% Organizes coarse time stamp data such that coinciding sections of each
% pixels' coarse time stamps (between -56 markers) are concatenated in a
% single variable
Data3 = cell(1,length(Ind{1,1}));
for j = 1:1:length(Ind{1,1})

    for i = 1:1:length(Ind)

        temp2 = Ind{1,i};
        temp = data{1,i};
        coarse = temp(:,2);
        fine = temp(:,1);
        if j == length(temp2)
            Sep = coarse(temp2(j):end-1); % A section of the coarse time stamps (between two -56 markers)

            fine2 = fine(temp2(j):end-1);
            Ind2 = find(fine2 == -9 | fine2 == -10); % Dwell clock markers are removed

            Sep(Ind2) = [];

        else

            Sep = coarse(temp2(j):temp2(j+1)-1); % A section of the coarse time stamps (between two -56 markers)
            fine2 = fine(temp2(j):temp2(j+1)-1);
            Ind2 = find(fine2 == -9 | fine2 == -10);
            Sep(Ind2) = [];
        end
        Data3{j} = [Data3{j} ; Sep];
    end
end

% Holds the numbers of nonzero events
Tot = zeros(1,20);

for k = 1:1:length(Data3)

    temp3 = Data3{1,k};

    [~,~,ix] = unique(temp3);
    C = accumarray(ix,1).';
    [~,~,ix] = unique(C);
    C2 = accumarray(ix,1).';

    temp4 = unique(temp3);

    Ind_temp = find(temp4 > 1e8); % Removes bad data points
    temp4(Ind_temp) = [];

    temp5 = diff(temp4)-1;
    Ind_temp2 = find(temp5 < 0);
    temp5(Ind_temp2) = [];


    Zero_Count(k) = sum(temp5(1:end-1)); % Number of zero detection events
    Tot(1:length(C2)) = Tot(1:length(C2)) + C2; % Number of nonzero detection events

end

hh = [sum(Zero_Count) Tot]; % Histogram of number of events for 0,1,2...

% ----------------------------------------------------------------------- %
% Complete the following code:
% Plot the histogram
figure

% -------------------------------- END ---------------------------------- %
